package nxu.it.controller;

import nxu.it.model.ApiResult;
import nxu.it.model.TodoItem;
import nxu.it.service.GreetingService;
import org.noear.solon.annotation.*;
import org.noear.solon.boot.web.MimeType;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;

import java.util.Random;

@Controller
public class MainController {

    @Inject
    GreetingService greetingService;

    @Mapping("/todo/list")
    @Get
    public ModelAndView list() {
        ModelAndView mv = new ModelAndView("todo_list.ftl");
        mv.put("todoItems", greetingService.getAllItems());
        return mv;
    }

    @Mapping("/todo/check/{id}")
    @Get
    public void toggleComplete(@Param int id, Context ctx) {
        TodoItem item = greetingService.getItemById(id);
        if (item != null) {
            item.setComplete(!item.isComplete());
            greetingService.updateItem(item);
            ctx.redirect("/todo/list");
        } else {
            ctx.redirect("/fail");
        }
    }

    @Mapping("/todo/edit/{id}")
    @Get
    public ModelAndView edit(@Param int id) {
        ModelAndView mv = new ModelAndView();
        TodoItem item = greetingService.getItemById(id);
        if (item != null) {
             mv = new ModelAndView("todo_edit.ftl");
            mv.put("todoItem", item);
        } else {
             mv = new ModelAndView("fail.ftl");
        }
        return mv;
    }

    @Mapping("/todo/update")
    @Post
    public void update(@Body TodoItem updatedItem, Context ctx) {
        TodoItem item = greetingService.getItemById(updatedItem.getId());
        if (item != null) {
            greetingService.updateItem(updatedItem);
            ctx.redirect("/todo/list");
        } else {
            ctx.redirect("/fail");
        }

    }

    @Mapping("/todo/save")
    @Post
    public void save(@Body TodoItem todoItem, Context ctx) {
        int nextId = greetingService.getNextId(); // 从服务层获取下一个可用的ID
        todoItem.setId(nextId); // 设置事项的ID
        todoItem.setComplete(false);
        greetingService.addItem(todoItem);
        ctx.redirect("/todo/list");
    }


    @Mapping("/todo/delete/{id}")
    @Get
    public void delete(@Param int id, Context ctx) {
        TodoItem item = greetingService.getItemById(id);
        if (item != null) {
            greetingService.deleteItem(id);
            ctx.redirect("/todo/list");
        } else {
            ctx.redirect("/fail");
        }

    }

    @Mapping("/fail")
    @Get
    public ModelAndView fail() {
        ModelAndView mv = new ModelAndView("fail.ftl");
        return mv;
    }
}